package com.platform.modules;

import com.platform.common.aspectj.SysLogEnum;
import com.platform.common.aspectj.SysLogRepeat;
import com.platform.common.config.CaptchaConfig;
import com.platform.common.exception.BaseException;
import com.platform.common.shiro.ShiroUtils;
import com.platform.common.validation.ValidateGroup;
import com.platform.common.validation.ValidationUtil;
import com.platform.common.web.controller.BaseController;
import com.platform.common.web.domain.AjaxResult;
import com.platform.common.web.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LENOVO
 * @title: MainController
 * @date 2019-08-2116:56
 */
@Controller
@Slf4j
public class SysLoginController extends BaseController {

    @Resource
    private CaptchaConfig captchaConfig;

    /**
     * 去主页面
     */
    @GetMapping("/toLogin")
    public String login() {
        return "login";
    }

    /**
     * 执行登录方法
     */
    @PostMapping("/login")
    @ResponseBody
    @SysLogRepeat(needLogin = false, moduleType = SysLogEnum.LOGIN, remark = "用户登录")
    public AjaxResult login(SysUserVo userVo) {
        try {
            ValidationUtil.validate(userVo, ValidateGroup.LOGIN.class);
        } catch (BaseException e) {
            return AjaxResult.loginFail(e.getMessage());
        }
        UsernamePasswordToken token = new UsernamePasswordToken(userVo.getUsername(), userVo.getPassword());
        try {
            Subject subject = ShiroUtils.getSubject();
            subject.login(token);
        } catch (IncorrectCredentialsException | UnknownAccountException e) {
            return AjaxResult.loginFail("账号或密码不正确");
        } catch (DisabledAccountException e) {
            return AjaxResult.loginFail(e.getMessage());
        } catch (Exception e) {
            log.error("登录未知异常" + e);
            return AjaxResult.loginFail("未知异常");
        }
        log.info("登录成功");
        return AjaxResult.successMsg("成功");
    }

    /**
     * 获取验证码
     */
    @GetMapping(value = "/getCaptcha")
    public void getCaptcha(HttpServletResponse response) throws IOException {
        captchaConfig.getCaptcha(response);
    }

}
